package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.ProcessInstanceDao;
import com.powerunion.datacollection.model.ActivityInfo;
import com.powerunion.datacollection.model.ActivityInstance;
import com.powerunion.datacollection.model.Urgency;
import com.powerunion.datacollection.model.jsonObject.ActivityTreeNode;
import com.powerunion.datacollection.model.jsonObject.ApproveTreeNode;
import com.powerunion.datacollection.model.jsonObject.CollectionTreeNode;
import com.powerunion.datacollection.model.jsonObject.TaskTrackDetails;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.datacollection.service.ApproveWorkItemManager;
import com.powerunion.datacollection.service.SubmissionWorkItemManager;
import com.powerunion.datacollection.service.UrgencyManager;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class ProcessInstanceDaoImpl extends JdbcBase implements
		ProcessInstanceDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			ProcessInstanceDaoImpl.class);

	private String sqlSave() {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"insert into dc_proc_instance(id,proc_id,item_id,para_id,act_type,act_name,time_limit,fillType_Or_appType,")
				.append(
						"appRole_Or_urgDate,examRol_Or_colRol,description,act_state,exa_Or_col_type,iupdata,urgency_content) ")
				.append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
		return sql.toString();
	}

	public boolean save(ActivityInstance activityInfo, String itemId,
			String procId, String exactlyTime) throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}
		Connection conn = null;

		String activityId = "";
		String sql = this.sqlSave();
		try {
			conn = this.getConnection();
			activityId = this.saveActivityInfo(activityInfo, sql, conn, "null",
					itemId, procId, exactlyTime);
		} catch (Exception e) {
			logger.error("", e);
			return false;
		} finally {
			DBUtils.close(conn);
		}

		if (!StringUtils.isEmpty(activityId)) {

			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "流程实例信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "流程实例信息"
						+ Constants.FAIL);
			}
			return false;
		}
	}

	private String saveActivityInfo(ActivityInstance activityInfo, String sql,
			Connection conn, String paraId, String itemId, String procId,
			String exactlyTime) throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "saveActivityInfo");
		}
		String resultId = "";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			int i = 1;
			resultId = String.valueOf(this.getSeq("dc_proc_instance"));
			logger.debug("开始保存id为：" + resultId + " 步骤名称："
					+ activityInfo.getActivityName());
			ps.setString(i++, resultId);
			ps.setString(i++, procId);
			ps.setString(i++, itemId);
			ps.setString(i++, paraId);
			ps.setInt(i++, activityInfo.getActivityType());
			ps.setString(i++, activityInfo.getActivityName());
			String timeLimit = Format.getInstance().exactlyDate(exactlyTime,
					activityInfo.getTimeLimit());
			ps.setString(i++, timeLimit);
			ps.setInt(i++, activityInfo.getFillTypeOrapproveType());
			String approveUserORurgencyDate = "";
			if (activityInfo.getActivityType() == Constants.COLLECTION_STEP_TYPE) {
				approveUserORurgencyDate = Format.getInstance()
						.exactlyDate(exactlyTime,
								activityInfo.getApproveUserOrurgencyDate());
			} else {
				approveUserORurgencyDate = activityInfo
						.getApproveUserOrurgencyDate();
			}

			ps.setString(i++, approveUserORurgencyDate);

			ps.setString(i++, activityInfo.getExamineUserOrcollectionUser());
			ps.setString(i++, activityInfo.getDescription());
			ps.setInt(i++, activityInfo.getActState());
			ps.setString(i++, activityInfo
					.getExamineUserOrcollectionUserTypes());
			ps.setInt(i++, activityInfo.getIupdata());

			ps.setString(i++, activityInfo.getUrgencyContent());

			ps.executeUpdate();

			if (activityInfo.getActivityType() != 0) {
				Urgency urgency = new Urgency();
				urgency.setProcId(itemId);
				urgency.setActId(resultId);
				urgency.setRemindInfo(activityInfo.getRemindContent());
				urgency.setUrgencyContent(activityInfo.getUrgencyContent());
				urgency.setRepeatCount(activityInfo.getRepeatCount());
				urgency.setRepeatIntervalDay(activityInfo
						.getRepeatIntervalDay());
				urgency.setRepeatIntervalHour(activityInfo
						.getRepeatIntervalHour());

				String urgenCyDate = Format.getInstance().exactlyDate(
						exactlyTime, activityInfo.getUrgencyDate());
				urgency.setUrgeTime(urgenCyDate);

				urgency.setType(1);
				UrgencyManager um = new UrgencyManager();
				um.save(urgency, conn);
			}

			if (activityInfo.getData() != null
					&& activityInfo.getData().size() > 0) {
				for (Iterator iter2 = activityInfo.getData().iterator(); iter2
						.hasNext();) {
					ActivityInstance ai = (ActivityInstance) iter2.next();
					String aiId = "";
					// 递归保存
					aiId = this.saveActivityInfo(ai, sql, conn, resultId,
							itemId, procId, exactlyTime);
					if (StringUtils.isEmpty(aiId))
						break;
				}
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存流程实例信息出错！");
		} finally {
			DBUtils.close(ps);
		}
		return resultId;
	}

	public List getProcessInfo(String processId) throws Exception {
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();

		sqlString
				.append(
						"select id,proc_id,item_id,para_id,act_type,act_name,time_limit,appRole_Or_urgDate,fillType_Or_appType,")
				.append(
						"examRol_Or_colRol,description,exa_Or_col_type,iupdata from dc_proc_instance where item_id=? and para_id=?");

		List activityList = null;
		try {
			conn = this.getConnection();
			activityList = new ArrayList();
			activityList = this.getTreeNodes(conn, processId, "null", sqlString
					.toString());
		} catch (Exception e) {
			logger.error("", e);
			throw new Exception(Constants.SEARCH + "getProcessInstance tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	// surveillance

	private List getTreeNodes(Connection conn, String processId, String paraId,
			String sql) throws Exception {
		logger.info(Constants.INTOMETHOD + "getTreeNodes");
		PreparedStatement ps = null;
		ResultSet rs = null;
		List treeNodeArray = null;

		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, processId);
			ps.setString(2, paraId);
			rs = ps.executeQuery();
			treeNodeArray = new ArrayList();

			while (rs.next()) {
				int activityType = rs.getInt("act_type");
				String id = rs.getString("id");
				String text = rs.getString("act_name");
				String description = rs.getString("description");
				String examineUserORcollectionUser = rs
						.getString("examRol_Or_colRol");
				String approveUserORurgencyDate = rs
						.getString("appRole_Or_urgDate");
				int fillTypeOrapproveType = rs.getInt("fillType_Or_appType");
				String timeLimit = rs.getString("time_limit");
				String examineUserORcollectionUserTypes = rs
						.getString("exa_Or_col_type");
				int iupdata = rs.getInt("iupdata");

				switch (activityType) {
				case 0:
					ActivityTreeNode treeNode = new ActivityTreeNode();
					treeNode.setId(id);
					treeNode.setText(text);
					treeNode.setDescription(description);
					treeNode.setIconCls("processStart");
					treeNode.setType("0");
					List children = new ArrayList();
					// 递归调用
					children = this.getTreeNodes(conn, processId, treeNode
							.getId(), sql);
					if (!children.isEmpty()) {
						treeNode.setChildren(children);
						treeNode.setLeaf(false);
					}
					treeNodeArray.add(treeNode);
					break;
				case 1:
					ApproveTreeNode at = new ApproveTreeNode();
					at.setId(id);
					at.setText(text);
					at.setDescription(description);
					at.setIconCls("approveNode");
					at.setType("1");
					at.setApproveDate(timeLimit);
					at.setApproveType("审批步骤");
					at.setApproveUserCodes(approveUserORurgencyDate);
					String approveUserNames = this
							.getApproveActivityUserNames(approveUserORurgencyDate);
					at.setApproveUserNames(approveUserNames);
					at.setAuditingType(fillTypeOrapproveType);
					at.setExamineUserCodes(examineUserORcollectionUser);
					String examineUserNames = this
							.getCollectionActivityUserNames(
									examineUserORcollectionUser,
									examineUserORcollectionUserTypes);
					at.setExamineUserNames(examineUserNames);
					at.setExamineUserTypes(examineUserORcollectionUserTypes);
					at.setExpandable(false);
					at.setIupdata(iupdata);

					List atChildren = new ArrayList();
					// 递归调用
					atChildren = this.getTreeNodes(conn, processId, at.getId(),
							sql);
					if (!atChildren.isEmpty()) {
						at.setChildren(atChildren);
						at.setLeaf(false);
					}
					treeNodeArray.add(at);
					break;
				case 2:
					CollectionTreeNode ct = new CollectionTreeNode();
					ct.setId(id);
					ct.setText(text);
					ct.setDescription(description);
					ct.setIconCls("collectionUserGroup");
					ct.setType("2");
					ct.setCollectionUserCodes(examineUserORcollectionUser);
					String collectionUserNames = this
							.getCollectionActivityUserNames(
									examineUserORcollectionUser,
									examineUserORcollectionUserTypes);
					ct.setCollectionUserNames(collectionUserNames);
					ct.setCollectionUserTypes(examineUserORcollectionUserTypes);
					ct.setDisposalDate(timeLimit);
					ct.setExpandable(false);
					ct.setFillType(fillTypeOrapproveType);
					ct.setUrgencyDate(approveUserORurgencyDate);
					ct.setCollectionType("采集节点");
					ct.setLeaf(true);
					treeNodeArray.add(ct);
					break;
				}

			}

			logger.debug(Constants.SEARCH + "processinfo tree"
					+ Constants.SUCCESS);

		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "流程实例信息" + Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}
		return treeNodeArray;
	}

	private String getApproveActivityUserNames(String userCodes)
			throws DaoException {

		// 参数为空
		if (StringUtils.isEmpty(userCodes)) {
			// String[] args = { "userCodes" };
			// // 打印错误日志
			// StringBuffer msglog = new StringBuffer(
			// "empty invoke parameter userCodes NULL ");
			// logger.error(msglog.toString());
			// throw new SystemException("error.common.parameter.empty", args);
			return "";
		}

		StringBuffer userNames = new StringBuffer();

		String[] users = StringUtils.split(userCodes, ",");
		Connection conn = null;
		try {
			conn = this.getConnection();
			String sql = "select f.user_name from frameuser f where f.user_code = ?";
			for (int i = 0; i < users.length; i++) {
				String userCode = users[i];
				QueryOperator query = new QueryOperator();
				query.setSql(sql);
				query.setPresentConnection(conn);
				query.setUseOnlyConnectionFlag(true);
				query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));
				query.access();

				if (query.resultSetAvailable()) {// 检查结果集是否可用
					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());

					if (rs.rowCount > 0) {
						String userName = rs.getFieldValueAsString("user_name");
						if (userNames.toString().trim().equals("")) {
							userNames.append(userName);
						} else {
							userNames.append(",").append(userName);
						}

					}
					rs.clearAll();

				}

			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getApproveActivityUserNames throw error!");
		} finally {
			DBUtils.close(conn);
		}

		return userNames.toString();
	}

	private String getCollectionActivityUserNames(String userCodes,
			String userTypes) throws DaoException {

		// 参数为空
		if (StringUtils.isEmpty(userCodes)) {
			// String[] args = { "userCodes" };
			// // 打印错误日志
			// StringBuffer msglog = new StringBuffer(
			// "empty invoke parameter userCodes NULL ");
			// logger.error(msglog.toString());
			// throw new SystemException("error.common.parameter.empty", args);
			return "";
		}

		StringBuffer userNames = new StringBuffer();

		String[] users = StringUtils.split(userCodes, ",");
		String[] types = StringUtils.split(userTypes, ",");
		Connection conn = null;
		try {
			conn = this.getConnection();
			String sql = "select f.user_name from frameuser f where f.user_code = ?";
			for (int i = 0; i < users.length; i++) {
				String code = users[i];
				String type = types[i];
				if (type.equals("user")) {
					sql = "select f.user_name name from frameuser f where f.user_code = ?";
				} else if (type.equals("group")) {
					sql = "select w.grop_name name from workgroup w where w.grop_code = ?";
				} else if (type.equals("department")) {
					sql = "select d.dept_name name from framedepartment d  where d.dept_code = ?";
				}

				QueryOperator query = new QueryOperator();
				query.setSql(sql);
				query.setPresentConnection(conn);
				query.setUseOnlyConnectionFlag(true);
				query.addParameter(new SqlParameter(SqlType.VARCHAR, code));
				query.access();

				if (query.resultSetAvailable()) {// 检查结果集是否可用
					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());

					if (rs.rowCount > 0) {
						String userName = rs.getFieldValueAsString("name");
						if (userNames.toString().trim().equals("")) {
							userNames.append(userName);
						} else {
							userNames.append(",").append(userName);
						}

					}
					rs.clearAll();

				}

			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getUsersByActivity throw error!");
		} finally {
			DBUtils.close(conn);
		}

		return userNames.toString();
	}

	public boolean delete(String doumentId) {

		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "delete");
		}
		String sql = "delete from dc_proc_instance where item_id = ? ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);

		update.addParameter(new SqlParameter(SqlType.VARCHAR, doumentId));

		update.access();
		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "流程实例信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "流程实例信息"
						+ Constants.FAIL);
			}
			return false;
		}
	}

	/**
	 * 得到流程实例的流程定义ID
	 * 
	 * @param item_id
	 * @return
	 * @throws DaoException
	 */
	public String getProcDefineId(String itemId) throws DaoException {
		String sql = "select proc_id from dc_proc_instance where item_id = ? ";
		QueryOperator query = new QueryOperator();
		query.setSql(sql);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, itemId));
		String procDefineId = "";

		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					procDefineId = rs.getFieldValueAsString("proc_id");
				}
				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("得到流程实例的原型流程定义信息的ID出错！");
		}
		return procDefineId;
	}

	/**
	 * 启动流程时 产生采集步骤的报送明细信息
	 * 
	 * @param processId
	 * @return
	 * @throws DaoException
	 */
	public boolean initSubmissionWorkItems(String processId, String formId)
			throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "initSubmissionWorkItems");
		}
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select id,item_id,description,act_name,filltype_or_apptype,")
				.append(
						"time_limit,approle_or_urgdate,examrol_or_colrol,exa_Or_col_type ")
				.append(
						" from dc_proc_instance where act_type = 2 and item_id = ?");
		Connection conn = null;
		QueryOperator query = new QueryOperator();
		query.setUseOnlyConnectionFlag(true);
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, processId));
		boolean flag = false;
		try {
			conn = this.getConnection();
			query.setPresentConnection(conn);
			query.access();

			SubmissionWorkItemManager sim = new SubmissionWorkItemManager();
			if (query.resultSetAvailable()) {// 检查结果集是否可用
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					ActivityInfo ai = new ActivityInfo();
					ai.setActivityId(rs.getFieldValueAsString("id"));
					ai.setProcId(rs.getFieldValueAsString("item_id"));
					ai.setDescription(rs.getFieldValueAsString("description"));
					ai.setActivityName(rs.getFieldValueAsString("act_name"));
					ai.setFillTypeOrapproveType(rs.getFieldValueAsInteger(
							"filltype_or_apptype").intValue());
					ai.setTimeLimit(rs.getFieldValueAsString("time_limit"));
					ai.setApproveUserOrurgencyDate(rs
							.getFieldValueAsString("approle_or_urgdate"));
					ai.setExamineUserOrcollectionUser(rs
							.getFieldValueAsString("examrol_or_colrol"));
					ai.setExamineUserOrcollectionUserTypes(rs
							.getFieldValueAsString("exa_Or_col_type"));

					sim.save(ai, formId, conn);
					rs.next();
				}

				rs.clearAll();
				flag = true;
			}
		} catch (Exception e) {
			logger.error("初始化采集任务实现异常！", e);
			throw new DaoException("初始化采集任务实现异常！");
		} finally {
			DBUtils.close(conn);
		}

		return flag;
	}

	public boolean saveProcessInfo(List activityList, String procId,
			String procInstanceId, String currentUser, String exactlyTime)
			throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "saveProcessInfo");
		}
		Connection conn = null;

		String activityId = "";
		try {
			conn = this.getConnection();
			for (Iterator iter = activityList.iterator(); iter.hasNext();) {
				ActivityInfo activityInfo = (ActivityInfo) iter.next();
				activityId = this.saveActivityInfo(activityInfo,
						this.sqlSave(), conn, "null", procId, procInstanceId,
						currentUser, exactlyTime);
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存流程实例环节信息出错！");
		} finally {
			DBUtils.close(conn);
		}

		if (!StringUtils.isEmpty(activityId)) {

			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "流程实例环节信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "流程实例环节信息"
						+ Constants.FAIL);
			}
			return false;
		}
	}

	private String saveActivityInfo(ActivityInfo activityInfo, String sql,
			Connection conn, String paraId, String procId,
			String procInstanceId, String currentUser, String exactlyTime)
			throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "saveActivityInfo");
		}
		String resultId = "";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			int i = 1;
			resultId = String.valueOf(this.getSeq("dc_proc_instance"));
			ps.setString(i++, resultId);
			ps.setString(i++, procId);
			ps.setString(i++, procInstanceId);
			ps.setString(i++, paraId);
			ps.setInt(i++, activityInfo.getActivityType());
			ps.setString(i++, activityInfo.getActivityName());
			// 根据任务的实际启动时间以及时限天数计算得到真实的时限日期
			String timeLimit = Format.getInstance().exactlyDate(exactlyTime,
					activityInfo.getTimeLimit());
			ps.setString(i++, timeLimit);

			ps.setInt(i++, activityInfo.getFillTypeOrapproveType());

			if (activityInfo.getActivityType() == 0) {// 如果是发起人节点，则把启动任务的用户存到appRole_Or_urgDate作为该流程发起人的用户
				ps.setString(i++, currentUser);
			} else {
				// String approveUserORurgencyDate =
				// Format.getInstance().exactlyDate(exactlyTime,activityInfo
				// .getApproveUserOrurgencyDate());

				ps.setString(i++, activityInfo.getApproveUserOrurgencyDate());
			}

			ps.setString(i++, activityInfo.getExamineUserOrcollectionUser());
			ps.setString(i++, activityInfo.getDescription());
			ps.setInt(i++, 0);
			ps.setString(i++, activityInfo
					.getExamineUserOrcollectionUserTypes());
			ps.setInt(i++, activityInfo.getIupdata());
			ps.setString(i++, activityInfo.getUrgencyContent());

			ps.executeUpdate();

			int activityType = activityInfo.getActivityType();
			if (activityType != 0) {

				Urgency urgency = new Urgency();
				urgency.setProcId(procInstanceId);
				urgency.setActId(resultId);
				urgency.setRemindInfo(activityInfo.getRemindContent());
				urgency.setUrgencyContent(activityInfo.getUrgencyContent());
				String urgeTime = Format.getInstance().exactlyDate(exactlyTime,
						activityInfo.getUrgencyDate());
				urgency.setUrgeTime(urgeTime);
				urgency.setType(1);
				urgency.setRepeatCount(activityInfo.getRepeatCount());
				urgency.setRepeatIntervalDay(activityInfo
						.getRepeatIntervalDay());
				urgency.setRepeatIntervalHour(activityInfo
						.getRepeatIntervalHour());
				UrgencyManager um = new UrgencyManager();
				um.save(urgency, conn);
			}

			if (activityInfo.getData() != null
					&& activityInfo.getData().size() > 0) {
				for (Iterator iter2 = activityInfo.getData().iterator(); iter2
						.hasNext();) {
					ActivityInfo ai = (ActivityInfo) iter2.next();
					String aiId = "";
					// 递归保存
					aiId = this.saveActivityInfo(ai, sql, conn, resultId,
							procId, procInstanceId, currentUser, exactlyTime);
					if (StringUtils.isEmpty(aiId))
						break;
				}
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("saveActivityInfo throw error!");
		} finally {
			DBUtils.close(ps);
		}
		return resultId;
	}

	/**
	 * 检测流程的环节信息设置
	 * 
	 * @param procId
	 * @return
	 * @throws DaoException
	 */
	public String validateActivityInfo(String procId) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "validateActivityInfo");
		StringBuffer sql = new StringBuffer();
		sql.append("select act_type,act_name,").append(
				"time_limit,appRole_Or_urgDate,examRol_Or_colRol ").append(
				"from dc_proc_instance where item_id = ?");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, procId));

		StringBuffer validateInfo = new StringBuffer();
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int j = 0; j < rs.rowCount; j++) {

					String timeLimit = rs.getFieldValueAsString("time_limit");
					String appRoleOrurgDate = rs
							.getFieldValueAsString("appRole_Or_urgDate");
					String examRolOrcolRol = rs
							.getFieldValueAsString("examRol_Or_colRol");
					String actName = rs.getFieldValueAsString("act_name");
					int actType = rs.getFieldValueAsInteger("act_type")
							.intValue();

					if (actType != 0) {
						if (StringUtils.isEmpty(timeLimit)
								|| StringUtils.isEmpty(appRoleOrurgDate)
								|| StringUtils.isEmpty(examRolOrcolRol)) {

							validateInfo.append("<font color=red>").append(
									actName).append("步骤</font>:");

							if (StringUtils.isEmpty(timeLimit)) {
								if (actType == 1) {// 审批步骤
									validateInfo
											.append("<font color=green>【审批时限】</font> 没有设置||");
								} else if (actType == 2) {// 采集步骤
									validateInfo
											.append("<font color=green>【处理时限】</font> 没有设置||");
								}
							}

							if (StringUtils.isEmpty(appRoleOrurgDate)) {
								if (actType == 1) {// 审批步骤
									validateInfo
											.append("<font color=green>【审批人】</font>没有设置||");
								}
								// else if (actType == 2) {//
								// validateInfo
								// .append("<font
								// color=green>【催办时限】</font>没有设置||");
								// }
							}

							if (StringUtils.isEmpty(examRolOrcolRol)) {
								if (actType == 2) {
									validateInfo
											.append("<font color=green>【采集人】</font>没有设置||");
								}
							}
							validateInfo.append(" <br> ");
						}
					}

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("检测流程Id为：" + procId + " 的环节步骤信息出错！");
		}
		return validateInfo.toString();
	}

	// public List getProcessSurveillanceInfo(String processId)
	// throws DaoException {
	// Connection conn = null;
	// StringBuffer sqlString = new StringBuffer();
	//
	// sqlString
	// .append(
	// "select id,para_id,act_type,act_name,appRole_Or_urgDate,")
	// .append(
	// "examRol_Or_colRol from dc_proc_instance where item_id=? and para_id=?
	// and act_state<>5");
	// List activityList = null;
	// try {
	// conn = this.getConnection();
	// activityList = new ArrayList();
	// activityList = this.getActivities(conn, processId, "null",
	// sqlString.toString());
	// } catch (Exception e) {
	// logger.error("", e);
	// throw new DaoException(Constants.SEARCH
	// + "getProcessSurveillanceInfo tree" + Constants.FAIL);
	// } finally {
	// DBUtils.close(conn);
	// }
	// return activityList;
	// }
	//
	// private List getActivities(Connection conn, String processId,
	// String paraId, String sql) throws DaoException {
	// PreparedStatement ps = null;
	// ResultSet rs = null;
	// List treeNodeArray = null;
	// ApproveWorkItemManager awim = null;
	// SubmissionWorkItemManager swim = null;
	// try {
	// awim = new ApproveWorkItemManager();
	// swim = new SubmissionWorkItemManager();
	// ps = conn.prepareStatement(sql);
	// ps.setString(1, processId);
	// ps.setString(2, paraId);
	// rs = ps.executeQuery();
	// treeNodeArray = new ArrayList();
	//
	// while (rs.next()) {
	// int activityType = rs.getInt("act_type");
	// String id = rs.getString("id");
	// String text = rs.getString("act_name");
	//
	// switch (activityType) {
	// case 0:
	// ActivityTreeNode treeNode = new ActivityTreeNode();
	// treeNode.setId(id);
	// treeNode.setText(text);
	// treeNode.setIconCls("processStart");
	// treeNode.setType("0");
	// List children = new ArrayList();
	// // 递归调用
	// children = this.getActivities(conn, processId, treeNode
	// .getId(), sql);
	// if (!children.isEmpty()) {
	// treeNode.setChildren(children);
	// treeNode.setLeaf(false);
	// }
	// treeNodeArray.add(treeNode);
	// break;
	// case 1:
	// ApproveTreeNode at = new ApproveTreeNode();
	// at.setId(id);
	// at.setText(text);
	// at.setIconCls("approveNode");
	// at.setType("1");
	// at.setApproveType("审批步骤");
	// at.setExpandable(false);
	//
	// List approveAct = awim.findApproveWorkIdByActivityId(id);
	// List atChildren = new ArrayList();
	// // 递归调用
	// atChildren = this.getActivities(conn, processId,
	// at.getId(), sql);
	// if (!approveAct.isEmpty()) {
	// if (!atChildren.isEmpty()) {
	// approveAct.addAll(atChildren);
	// }
	// at.setChildren(approveAct);
	// at.setLeaf(false);
	// } else if (!atChildren.isEmpty()) {
	// at.setChildren(atChildren);
	// at.setLeaf(false);
	// }
	//
	// treeNodeArray.add(at);
	// break;
	// case 2:
	// CollectionTreeNode ct = new CollectionTreeNode();
	// ct.setId(id);
	// ct.setText(text);
	// ct.setIconCls("collectionUserGroup");
	// ct.setType("2");
	//
	// ct.setExpandable(false);
	// ct.setCollectionType("采集节点");
	// List collAct = swim.findSubmissionWorkIdByActivityId(id);
	// if (!collAct.isEmpty()) {
	// ct.setChildren(collAct);
	// ct.setLeaf(false);
	// } else {
	// ct.setLeaf(true);
	// }
	//
	// treeNodeArray.add(ct);
	// break;
	// }
	//
	// }
	//
	// logger.debug(Constants.SEARCH + "processinfo tree"
	// + Constants.SUCCESS);
	//
	// } catch (Exception e) {
	// logger.error("getTree() of throws : ", e);
	// throw new DaoException(Constants.SEARCH + "监控流程实例信息"
	// + Constants.FAIL);
	// } finally {
	// DBUtils.close(rs, ps);
	// }
	// return treeNodeArray;
	// }

	public List getProcessSurveillanceInfo(String processId)
			throws DaoException {
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();

		sqlString
				.append(
						"select id,para_id,act_type,act_name,appRole_Or_urgDate,")
				.append(
						"examRol_Or_colRol,description from dc_proc_instance where item_id=? and para_id=? and act_state<>5");
	
		List activityList = null;
		try {
			conn = this.getConnection();
			activityList = new ArrayList();
			activityList = this.getActivities(conn, processId, "null",
					sqlString.toString());
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException(Constants.SEARCH
					+ "getProcessSurveillanceInfo tree" + Constants.FAIL);
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	private List getActivities(Connection conn, String processId,
			String paraId, String sql) throws DaoException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		List treeNodeArray = null;
		ApproveWorkItemManager awim = null;
		SubmissionWorkItemManager swim = null;
		try {
			awim = new ApproveWorkItemManager();
			swim = new SubmissionWorkItemManager();
			ps = conn.prepareStatement(sql);
			ps.setString(1, processId);
			ps.setString(2, paraId);
			rs = ps.executeQuery();
			treeNodeArray = new ArrayList();

			while (rs.next()) {
				int activityType = rs.getInt("act_type");
				String id = rs.getString("id");
				String text = rs.getString("act_name");
				TaskTrackDetails detail = new TaskTrackDetails();
				detail.setUiProvider("col");
				switch (activityType) {
				case 0:
					
					detail.setId(id);
					detail.setText(text);
					detail.setIconCls("processStart");
					detail.setType(0);
					List children = new ArrayList();
					// 递归调用
					children = this.getActivities(conn, processId, detail
							.getId(), sql);
					if (!children.isEmpty()) {
						detail.setChildren(children);
						detail.setLeaf(false);
					}
					
					treeNodeArray.add(detail);
					break;
				case 1:
		
					detail.setId(id);
					detail.setText(text);
					detail.setIconCls("approveNode");
					detail.setType(1);
					detail.setExpandable(false);

					List approveAct = awim.findApproveWorkIdByActivityId(id);
					List atChildren = new ArrayList();
					// 递归调用
					atChildren = this.getActivities(conn, processId,
							detail.getId(), sql);
					if (!approveAct.isEmpty()) {
						if (!atChildren.isEmpty()) {
							approveAct.addAll(atChildren);
						}
						detail.setChildren(approveAct);
						detail.setLeaf(false);
					} else if (!atChildren.isEmpty()) {
						detail.setChildren(atChildren);
						detail.setLeaf(false);
					}
					
					treeNodeArray.add(detail);
					break;
				case 2:
					detail.setId(id);
					detail.setText(text);
					detail.setIconCls("collectionUserGroup");
					detail.setType(2);

					detail.setExpandable(false);
					//detail.setCollectionType("采集节点");
					List collAct = swim.findSubmissionWorkIdByActivityId(id);
					if (!collAct.isEmpty()) {
						detail.setChildren(collAct);
						detail.setLeaf(false);
					} else {
						detail.setLeaf(true);
					}

					treeNodeArray.add(detail);
					break;
				}

			}

			logger.debug(Constants.SEARCH + "processinfo tree"
					+ Constants.SUCCESS);

		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new DaoException(Constants.SEARCH + "监控流程实例信息"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}
		return treeNodeArray;
	}

	public List getTaskDetails(String processId) throws Exception {
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();

		sqlString
				.append(
						"select id,item_id,para_id,act_type,act_name,time_limit,appRole_Or_urgDate,fillType_Or_appType,")
				.append(
						"examRol_Or_colRol,description from dc_proc_instance where item_id=? and para_id=?");
		List activityList = null;
		try {
			conn = this.getConnection();
			activityList = new ArrayList();
			activityList = this.getDetails(conn, processId, "null", sqlString
					.toString());
		} catch (Exception e) {
			logger.error("", e);
			throw new Exception("getTaskDetails throw error!");
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	private List getDetails(Connection conn, String processId, String paraId,
			String sql) throws Exception {
		logger.info(Constants.INTOMETHOD + "getDetails");
		PreparedStatement ps = null;
		ResultSet rs = null;
		List treeNodeArray = null;

		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, processId);
			ps.setString(2, paraId);
			rs = ps.executeQuery();
			treeNodeArray = new ArrayList();

			while (rs.next()) {

				int activityType = rs.getInt("act_type");
				String id = rs.getString("id");
				String text = rs.getString("act_name");
				String description = rs.getString("description");
				String examineUserORcollectionUser = rs
						.getString("examRol_Or_colRol");
				String approveUserORurgencyDate = rs
						.getString("appRole_Or_urgDate");
				String timeLimit = rs.getString("time_limit");

				switch (activityType) {
				case 0:
					ActivityTreeNode treeNode = new ActivityTreeNode();
					treeNode.setId(id);
					treeNode.setText(text);
					treeNode.setDescription(description);
					treeNode.setIconCls("processStart");
					treeNode.setTimeLimit(timeLimit);
					treeNode.setType("0");
					treeNode.setUiProvider("col");

					List children = new ArrayList();
					// 递归调用
					children = this.getDetails(conn, processId, treeNode
							.getId(), sql);
					if (!children.isEmpty()) {
						treeNode.setChildren(children);
						treeNode.setLeaf(false);
					}
					treeNodeArray.add(treeNode);
					break;
				case 1:
					ActivityTreeNode approveNode = new ActivityTreeNode();

					approveNode.setId(id);
					approveNode.setText(text);
					approveNode.setDescription(description);
					approveNode.setIconCls("approveNode");
					approveNode.setType("1");
					approveNode.setTimeLimit(timeLimit);
					approveNode.setExpandable(false);
					approveNode
							.setApproveUserOrurgencyDate(approveUserORurgencyDate);
					approveNode.setUiProvider("col");

					List approveAct = this.getUsersByActivity(approveNode);
					List atChildren = new ArrayList();
					// 递归调用
					atChildren = this.getDetails(conn, processId, id, sql);
					if (!approveAct.isEmpty()) {
						if (!atChildren.isEmpty()) {
							approveAct.addAll(atChildren);
						}
						approveNode.setChildren(approveAct);
						approveNode.setLeaf(false);
					} else if (!atChildren.isEmpty()) {
						approveNode.setChildren(atChildren);
						approveNode.setLeaf(false);
					}
					// 步骤不需要显示时间
					approveNode.setTimeLimit("");
					treeNodeArray.add(approveNode);
					break;
				case 2:
					ActivityTreeNode collectNode = new ActivityTreeNode();

					collectNode.setId(id);
					collectNode.setText(text);
					collectNode.setDescription(description);
					collectNode.setIconCls("collectionUserGroup");
					collectNode.setType("2");
					collectNode.setTimeLimit(timeLimit);
					collectNode.setExpandable(false);
					collectNode
							.setExamineUserOrcollectionUser(examineUserORcollectionUser);
					collectNode.setUiProvider("col");

					List ctChildren = this.getUsersByActivity(collectNode);
					collectNode.setChildren(ctChildren);
					collectNode.setTimeLimit("");
					treeNodeArray.add(collectNode);
					break;
				}

			}

			logger.debug(Constants.SEARCH + "processinfo tree"
					+ Constants.SUCCESS);

		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "processinfo tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}
		return treeNodeArray;
	}

	private List getUsersByActivity(ActivityTreeNode at) throws DaoException {
		// 参数为空
		if (at == null) {
			String[] args = { "at" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter at NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		int type = Integer.parseInt(at.getType());
		String userStr = "";
		if (type == Constants.APPROVE_STEP_TYPE) {
			userStr = at.getApproveUserOrurgencyDate();
		} else if (type == Constants.COLLECTION_STEP_TYPE) {
			userStr = at.getExamineUserOrcollectionUser();
		}

		List userActivities = new ArrayList();
		if (!StringUtils.isEmpty(userStr)) {
			String[] users = StringUtils.split(userStr, ",");
			Connection conn = null;
			try {
				conn = this.getConnection();
				String sql = "select f.user_name from frameuser f where f.user_code = ?";
				for (int i = 0; i < users.length; i++) {
					String userCode = users[i];
					QueryOperator query = new QueryOperator();
					query.setSql(sql);
					query.setPresentConnection(conn);
					query.setUseOnlyConnectionFlag(true);
					query.addParameter(new SqlParameter(SqlType.VARCHAR,
							userCode));
					query.access();

					if (query.resultSetAvailable()) {// 检查结果集是否可用
						// 获取并处理记录集
						RsDataSet rs = new RsDataSet(query.getSqlResultSet());
						ActivityTreeNode atn = new ActivityTreeNode();
						if (rs.rowCount > 0) {
							String userName = rs
									.getFieldValueAsString("user_name");
							atn.setText(userName);
							if (type == Constants.APPROVE_STEP_TYPE) {
								atn.setIconCls("workGroup");
								atn.setType("11");
							} else if (type == Constants.COLLECTION_STEP_TYPE) {
								atn.setIconCls("collectionUserGroup");
								atn.setType("22");
							}

							atn.setTimeLimit(at.getTimeLimit());
							atn.setLeaf(true);
							atn.setUiProvider("col");

							userActivities.add(atn);
						}

						rs.clearAll();

					}

				}
			} catch (Exception e) {
				logger.error("", e);
				throw new DaoException("getUsersByActivity throw error!");
			} finally {
				DBUtils.close(conn);
			}

		}
		return userActivities;

	}

}
